package com.app.mingluxing.babytree;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.app.mingluxing.R;
import com.app.mingluxing.adapter.ImageAdapter;
import com.app.mingluxing.adapter.MyAdapter;
import com.app.mingluxing.base.BaseActivity;
import com.app.mingluxing.bean.BindChildList;
import com.app.mingluxing.bean.BitmapDetail;
import com.app.mingluxing.bean.ReleaseReq;
import com.app.mingluxing.bean.ResultBaseBean;
import com.app.mingluxing.bean.UploadBean;
import com.app.mingluxing.home.ChooseBabyActivity;
import com.app.mingluxing.message.ChoosePhotoActivity;
import com.app.mingluxing.net.HttpUtil;
import com.app.mingluxing.utils.CommonUtils;
import com.app.mingluxing.utils.Constant;
import com.app.mingluxing.utils.LogUtil;
import com.app.mingluxing.widget.ActionSheetDialog;
import com.app.mingluxing.widget.GridViewForScrollView;
import com.app.mingluxing.widget.PreviewPhotoActivity;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 宝宝树 发布页面
 * Created by Aaron on 15/7/30.
 */
public class ReleaseActivity extends BaseActivity {

    private static final int CHOOSE_BABY_CODE = 0x10001;
    private static final int CHOOSE_LOCATION = 0x10002;
    private static final int CHOOSE_TITLE = 0x10003;
    private Intent mIntent;
    private TextView tv_location;
    private TextView tv_babys;
    private TextView tv_theme;
    private List<BindChildList.Data> chooseedPeoples;
    private GridViewForScrollView gv_photos;
    private ArrayList<BitmapDetail> bitmapList;
    private ArrayList<String> id = new ArrayList<String>();
    private ArrayList<String> url = new ArrayList<String>();
    //    private String path;
    //    private ArrayList<String> PicUrl = new ArrayList<String>();
    private BitmapDetail addBitmapDeail;
    private ImageAdapter imageAdapter;
    //存放上传的图片的集合
    public List<BitmapDetail> loadedPics = new ArrayList<BitmapDetail>();
    /*相册选择的code*/
    private static final int PHOTO_ALBUM_CODE = 0x1011;
    /*拍照的code*/
    private static final int TAKE_PHOTO_CODE = 0x1012;
    //    //图片上传成功的code
//    private static final int LOADSUCCESS = 100132;
//    //图片上传失败的code
//    private static final int LOADERR = 100133;
    /*拍照的文件保存的位置*/
    private File currentFile;
    private ProgressDialog pdialog;
//    private ExecutorService executor;
//    private StringBuilder sbId;
    /**
     * 当前上传的图片的个数
     */
    int currentUpPic = 0;
    //需要上传的图片的数量
    private int uploadCount;
    private EditText et_content;
    //所选主题的id
    private String themeID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_release);
        initWidget();

        initGrideView();

        //拍照片
        String takePhoto = getIntent().getStringExtra("take_photo");

        if (!CommonUtils.isNull(takePhoto)) {
            //有拍照片
            pdialog = ProgressDialog.show(this, "", "图片上传中...");
            loadPicToNet(takePhoto);
        }


        ArrayList<String> choosePhotos = getIntent().getStringArrayListExtra("choose_photo");
        if (choosePhotos != null && choosePhotos.size() > 0) {
            //有选择照片
            handleChoosedPhoto(choosePhotos);
        }

        //选择默认的宝宝
        tv_babys.setText(sp.getString(Constant.CURRENTCHILDNAME, ""));
        id.add(sp.getString(Constant.CURRENTCHILDID, ""));

//        EventBus.getDefault().register(this);
    }

    private void initWidget() {

        TextView tv_left = (TextView) findViewById(R.id.tv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        TextView tv_right = (TextView) findViewById(R.id.tv_right);

        tv_left.setText(getResources().getString(R.string.cancle));
        tv_title.setText(getResources().getString(R.string.baby_tree_release));
        tv_right.setText(getResources().getString(R.string.baby_tree_release));

        RelativeLayout rl_location = (RelativeLayout) findViewById(R.id.rl_location);
        RelativeLayout rl_babys = (RelativeLayout) findViewById(R.id.rl_babys);
        RelativeLayout rl_title = (RelativeLayout) findViewById(R.id.rl_title);

        gv_photos = (GridViewForScrollView) findViewById(R.id.gv_photos);

        et_content = (EditText) findViewById(R.id.et_content);

        tv_location = (TextView) findViewById(R.id.tv_location);
        tv_babys = (TextView) findViewById(R.id.tv_babys);
        tv_theme = (TextView) findViewById(R.id.tv_theme);

        tv_left.setOnClickListener(this);
        tv_right.setOnClickListener(this);

        rl_location.setOnClickListener(this);
        rl_babys.setOnClickListener(this);
        rl_title.setOnClickListener(this);

    }

    /**
     * 初始化GrideView
     */
    private void initGrideView() {

        bitmapList = new ArrayList<BitmapDetail>();

//      //  先添加 + 号图片
//        Bitmap addBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_add);
        addBitmapDeail = new BitmapDetail(Constant.ADDBITMAPPATH, Constant.ADDBITMAPPATH);

        bitmapList.add(addBitmapDeail);
        imageAdapter = new ImageAdapter(this, bitmapList, pics);
        gv_photos.setAdapter(imageAdapter);

        gv_photos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //点击的是图片的最后一个
                if (loadedPics.size() == 0 || loadedPics.size() == position) {

                    if (loadedPics.size() == 9) {
                        Intent mIntent = new Intent(ReleaseActivity.this, PreviewPhotoActivity.class);
                        mIntent.putExtra("position", position);
                        mIntent.putExtra("lists", (Serializable) loadedPics);
                        startActivity(mIntent);
                        return;
                    }

                    //添加照片 弹出选择对话框
                    showChoose();

                } else {

                    //查看照片
                    Intent mIntent = new Intent(ReleaseActivity.this, PreviewPhotoActivity.class);
                    mIntent.putExtra("position", position);
                    mIntent.putExtra("lists", (Serializable) loadedPics);
                    startActivity(mIntent);

                }
            }
        });

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.tv_left:

                abandonEdit();

                break;
            case R.id.tv_right://发布

                release();

                break;
            case R.id.rl_location://所在位置

                mIntent = new Intent(this, LocationActivity.class);
                startActivityForResult(mIntent, CHOOSE_LOCATION);

                break;
            case R.id.rl_babys://选择宝宝

                mIntent = new Intent(this, ChooseBabyActivity.class);
                mIntent.putStringArrayListExtra("ids", id);
                startActivityForResult(mIntent, CHOOSE_BABY_CODE);

                break;
            case R.id.rl_title://选择标题

                mIntent = new Intent(this, ChooseTitleActivity.class);
                startActivityForResult(mIntent, CHOOSE_TITLE);

                break;
        }
    }

    /**
     * 发布
     */
    private void release() {

        if (CommonUtils.isNull(et_content.getText().toString().trim())
                && loadedPics.size() == 0) {
            showToast("请填写内容或选择照片");
            return;
        }
        if (CommonUtils.isNull(tv_babys.getText().toString().trim())) {
            showToast("请选择宝宝");
            return;
        }
        if (CommonUtils.isNull(tv_theme.getText().toString().trim())) {
            showToast("请选择标题");
            return;
        }

        ReleaseReq releaseReq = new ReleaseReq();
        releaseReq.token = sp.getString(Constant.TOKEN, "");
        releaseReq.address = CommonUtils.isNull(tv_location.getText().toString().trim()) ? "" : tv_location.getText().toString().trim();
        releaseReq.content = et_content.getText().toString().trim();//发布内容

//        if (chooseedPeoples == null || chooseedPeoples.size() == 0)
//            return;

        releaseReq.childerList = id;
//        releaseReq.childerList = sbId.toString().substring(0, sbId.length() - 1);

        releaseReq.type = themeID;//选择标题

        //图片
//        StringBuilder urls = new StringBuilder();
        for (BitmapDetail b : loadedPics) {
//            urls.append(b.urlPath + ",");
            url.add(b.urlPath);
        }
//        releaseReq.imgList = loadedPics.size() == 0 ? "" : urls.toString().substring(0, urls.length() - 1);
        releaseReq.imgList = url;

        HttpUtil.setPostRequest("发布中...", this, Constant.WEB_ROOT + Constant.SENDTREE, JSONObject.toJSONString(releaseReq), getClass().getName(),
                new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            ResultBaseBean resultBaseBean = JSONObject.parseObject(str, ResultBaseBean.class);

                            if (resultBaseBean.code == Constant.STATUS_SUCCESS) {

                                showToast("发布成功");

                                EventBus.getDefault().post(1);
                                finish(); //发布成功后返回上一页面

                            } else {
                                showToast(Constant.showErrorMsg(resultBaseBean.code, ReleaseActivity.this));
                            }

                        } catch (Exception e) {

                            e.printStackTrace();
                            showToast(Constant.NODATA);
                        }

                    }
                }, null);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case CHOOSE_BABY_CODE://选择宝宝
                if (data == null)
                    return;
                //获得到选中的接受人
                chooseedPeoples = (List<BindChildList.Data>) data.getSerializableExtra("children");

                if (chooseedPeoples == null || chooseedPeoples.size() < 1)
                    return;

                StringBuilder sb_baby = new StringBuilder();
//                sbId = new StringBuilder();

                id.clear();
                for (BindChildList.Data p : chooseedPeoples) {

                    id.add(p.id);
                    sb_baby.append(p.nickName + ",");

                }
                tv_babys.setText(sb_baby.toString().substring(0, sb_baby.length() - 1));

                break;

            case CHOOSE_LOCATION://选择位置

                if (data == null)
                    return;

                String location = data.getStringExtra("location");
                tv_location.setText(location);

                break;

            case TAKE_PHOTO_CODE: //拍照
                //上传图片
                if (currentFile != null && currentFile.exists()) {
                    pdialog = ProgressDialog.show(this, "", "图片上传中...");
                    loadPicToNet(currentFile.getPath());

//                LogUtil.e("TAG", "拍照的图片的地址====>>>" + currentFile.getPath());

                }
                break;

            case PHOTO_ALBUM_CODE://相册选择

                if (data == null) {
                    clearCachePhoto();
                    return;
                }

                //获取到传过来的图片的集合
                ArrayList<String> tempPhotos = data.getStringArrayListExtra("selectedPhotos");
                handleChoosedPhoto(tempPhotos);

                break;

            case CHOOSE_TITLE://选择主题

                if (data == null)
                    return;

                themeID = data.getStringExtra("themeID");

                tv_theme.setText(data.getStringExtra("tName"));

                break;
        }

    }

    public void clearCachePhoto() {
        //循环myadapter里面的所选择图片的路径
//        for (String paths : MyAdapter.mSelectedImage) {

        //如果pics里面存在myadapter里面的所选择图片的路径,则不清除所选图片

        Iterator<String> it = MyAdapter.mSelectedImage.iterator();
//
        while (it.hasNext()) {
            //it是迭代器你把集合中的所有元素都装入迭代器中
            //it.next()是迭代器提供给你的去他里面元素的方法
            String next = it.next();
            if (pics.contains(next)) {

                continue;
            } else
                it.remove();
//            MyAdapter.mSelectedImage.remove(next);
        }
    }

    private List<String> pics = new ArrayList<String>();


    /**
     * 处理相册选择的图片
     *
     * @param tempPhotos
     */
    private void handleChoosedPhoto(ArrayList<String> tempPhotos) {

        if (tempPhotos != null && tempPhotos.size() > 0) {

            for (String path : tempPhotos) {

                if (pics.contains(path)) {
                    //上传过
                    continue;
                } else {
                    pics.add(path);

                    if (++uploadCount == 1) {//上传个数+1, 如果是第一张图片就显示转圈
                        pdialog = ProgressDialog.show(this, "", "图片上传中...");
                    }

                    loadPicToNet(path);

                }
//
            }

        }

    }

    /**
     * 上传图片
     *
     * @param picturePath 该图片在手机上的地址
     */
    private void loadPicToNet(String picturePath) {

//        executor.execute(loadToNet(CommonUtils.compressByte(CommonUtils.getBitmapFromPath(picturePath)), picturePath));
        loadToNet(CommonUtils.compressByte(CommonUtils.getBitmapFromPath(picturePath)), picturePath);
    }


    /**
     * 获取上传的token 并上传图片
     *
     * @param bytes       上传图片的 字节码
     * @param picturePath 上传图片的本地地址
     */
    private void loadToNet(final byte[] bytes, final String picturePath) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest("加载中...", ReleaseActivity.this, Constant.WEB_ROOT + "uploadToken", j.toJSONString()
                , getClass().getName(),
                new HttpUtil.SuccessListener() {

                    @Override
                    public void setOnSuccessListener(String str) {

                        final UploadBean uploadBean = JSONObject.parseObject(str, UploadBean.class);

                        if (uploadBean.code == Constant.STATUS_SUCCESS) {

                            UploadManager uploadManager = new UploadManager();

                            uploadManager.put(bytes, uploadBean.path, uploadBean.token,
                                    new UpCompletionHandler() {
                                        @Override
                                        public void complete(String s, ResponseInfo responseInfo, org.json.JSONObject jsonObject) {

                                            if (responseInfo.isOK()) {


                                                //最后一张图片才会销毁 dialog
                                                if (++currentUpPic >= uploadCount) {

                                                    if (pdialog != null && pdialog.isShowing()) {

                                                        pdialog.dismiss();
                                                        LogUtil.e("TAG", "消失了???==>" + currentUpPic + ",,=>" + uploadCount);

                                                        currentUpPic = 0;
                                                        uploadCount = 0;

                                                    }
                                                }

                                                addPicToPage(new BitmapDetail(picturePath, uploadBean.domain + uploadBean.path));

                                            } else {
                                                showToast("图片上传失败");
                                            }

                                        }

                                    }, null);

                        } else {
                            showToast(Constant.showErrorMsg(uploadBean.code, ReleaseActivity.this));
                        }

                    }
                }, null);

    }


    /**
     * 页面上添加图片
     *
     * @param mBitmapDetail BitmapDetail对象,包含了图片的本地路径和url路径
     */
    private void addPicToPage(BitmapDetail mBitmapDetail) {

        // 先移除用来添加的图标，再添加以保证添加的图片始终在最后
        if (bitmapList.size() > 0)
            bitmapList.remove(bitmapList.size() - 1);
        //上传成功后再添加图片
        bitmapList.add(mBitmapDetail);
        loadedPics.add(mBitmapDetail);
//        LogUtil.e("TAG", "添加的图片的路径的====>" + mBitmapDetail.mPath);

        //如果有效图片小于9张 就添加 + 号图片
        if (bitmapList.size() < 9) {
            bitmapList.add(addBitmapDeail);
        }
        //
        imageAdapter.setBitmapsDetail(bitmapList, pics);
        imageAdapter.notifyDataSetChanged();

    }

    /**
     * 弹出选择照片的对话框
     */
    protected void showChoose() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 拍照
                                getTakePhoto();

                            }
                        })
                .addSheetItem("去相册选择", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 从相册中选择
                                getFromPhotoAlbum();
                            }
                        }).show();

    }

    /**
     * 拍照
     */
    private void getTakePhoto() {

        String cacheDir = Environment.getExternalStorageDirectory().getPath() + "/mlxCache";
        File photoFile = new File(cacheDir);
        //文件夹不存在就创建文件夹
        if (!photoFile.exists()) {
            photoFile.mkdirs();
        }
        //创建存放图片的jpg文件
        currentFile = new File(photoFile, System.currentTimeMillis() + ".jpg");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentFile));
        startActivityForResult(intent, TAKE_PHOTO_CODE);
    }

    /**
     * 从相册中选择
     */
    private void getFromPhotoAlbum() {

        Intent intent = new Intent(this, ChoosePhotoActivity.class);
        startActivityForResult(intent, PHOTO_ALBUM_CODE);

    }

    @Override
    public void onBackPressed() {

        abandonEdit();
    }

    /**
     * 放弃编辑
     */
    private void abandonEdit() {

        //如果用户未编辑过内容, 直接退出 && CommonUtils.isNull(tv_babys.getText().toString().trim())
        if (CommonUtils.isNull(et_content.getText().toString().trim()) && CommonUtils.isNull(tv_location.getText().toString().trim())
                && CommonUtils.isNull(tv_theme.getText().toString().trim()) &&
                gv_photos.getChildCount() == 1) {

            finish();

        } else {
            //用户编辑过,给出提示
            new AlertDialog.Builder(this).setMessage("要放弃本次编辑吗").setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();
                }
            }).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        MyAdapter.mSelectedImage.clear();
        mApplication.cancelPendingRequests(getClass().getName());

    }
}
